<script setup name="Dict" lang="ts">
import { DeleteOutlined, FormOutlined } from '@ant-design/icons-vue'
import { parseTime } from '../../../utils/ruoyi.ts'
import useDictStore from '@/stores/modules/dict'
import { addType, delType, getType, listType, refreshCache, updateType } from '@/api/system/dict/type'
import type { DictTypeForm, DictTypeQuery, DictTypeVO } from '@/api/system/dict/type/types'

const message = useMessage()
const modal = useModal()

const typeList = ref<DictTypeVO[]>([])
const loading = ref(true)
const ids = ref<Array<number | string>>([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const dictFormRef = ref()
const queryFormRef = ref()

const dialog = reactive<DialogOption>({
  visible: false,
  title: '',
})

const initFormData: DictTypeForm = {
  dictId: undefined,
  dictName: '',
  dictType: '',
  remark: '',
}
const data = reactive<PageData<DictTypeForm, DictTypeQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    dictName: '',
    dictType: '',
  },
  rules: {
    dictName: [{ required: true, message: '字典名称不能为空', trigger: 'blur' }],
    dictType: [{ required: true, message: '字典类型不能为空', trigger: 'blur' }],
  },
})

const { queryParams, form, rules } = toRefs(data)

/** 查询字典类型列表 */
function getList() {
  loading.value = true
  listType(queryParams.value).then((res) => {
    typeList.value = res.rows
    total.value = res.total
    loading.value = false
  })
}

/** 取消按钮 */
function cancel() {
  reset()
  dialog.visible = false
}

/** 表单重置 */
function reset() {
  form.value = { ...initFormData }
  dictFormRef.value?.resetFields()
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  queryFormRef.value?.resetFields()
  handleQuery()
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  dialog.visible = true
  dialog.title = '添加字典类型'
}

/** 多选框选中数据 */
function handleSelectionChange(selection: DictTypeVO[]) {
  ids.value = selection.map(item => item.dictId)
  single.value = selection.length !== 1
  multiple.value = !selection.length
}

/** 修改按钮操作 */
async function handleUpdate(row?: DictTypeVO) {
  reset()
  const dictId = row?.dictId || ids.value[0]
  const res = await getType(dictId)
  Object.assign(form.value, res.data)
  dialog.visible = true
  dialog.title = '修改字典类型'
}

/** 提交按钮 */
function submitForm() {
  dictFormRef.value.validate().then(async () => {
    form.value.dictId ? await updateType(form.value) : await addType(form.value)
    message.success('操作成功')
    dialog.visible = false
    getList()
  }).catch()
}

/** 删除按钮操作 */
async function handleDelete(row?: DictTypeVO) {
  const dictIds = row?.dictId || ids.value
  modal.confirm({
    title: `是否确认删除字典编号为"${dictIds}"的数据项？`,
    onOk: async () => {
      await delType(dictIds)
      getList()
      message.success('删除成功')
    },
  })
}

/** 刷新缓存按钮操作 */
async function handleRefreshCache() {
  await refreshCache()
  message.success('刷新成功')
  useDictStore().cleanDict()
}

onMounted(() => {
  getList()
})
</script>

<template>
  <div class="p-2">
    <a-card class="mb-20px">
      <div class="flex flex-between">
        <a-form ref="queryFormRef" class="inline-form" :model="queryParams" layout="inline" label-width="68px">
          <a-form-item label="字典名称" prop="dictName">
            <a-input
              v-model:value="queryParams.dictName" placeholder="请输入字典名称" clearable style="width: 240px"
              @keyup.enter="handleQuery"
            />
          </a-form-item>
          <a-form-item label="字典类型" prop="dictType">
            <a-input
              v-model:value="queryParams.dictType" placeholder="请输入字典类型" clearable style="width: 240px"
              @keyup.enter="handleQuery"
            />
          </a-form-item>
          <a-form-item>
            <a-button type="primary" class="mr-10px" @click="handleQuery">
              搜索
            </a-button>
            <a-button @click="resetQuery">
              重置
            </a-button>
          </a-form-item>
        </a-form>
        <a-row :gutter="10">
          <a-col>
            <a-button v-hasPermi="['system:dict:add']" type="primary" plain @click="handleAdd">
              新增
            </a-button>
          </a-col>
          <a-col>
            <a-button v-hasPermi="['system:dict:remove']" @click="handleRefreshCache">
              刷新缓存
            </a-button>
          </a-col>
        </a-row>
      </div>
    </a-card>
    <a-card>
      <a-table :loading="loading" :pagination="false" :data-source="typeList" @selection-change="handleSelectionChange">
        <a-table-column title="字典名称" data-index="dictName" :ellipsis="true" />
        <a-table-column title="字典类型" align="center" :ellipsis="true">
          <template #default="{ record }">
            <router-link :to="`/system/dict-data/index/${record.dictId}`" class="link-type">
              <span>{{ record.dictType }}</span>
            </router-link>
          </template>
        </a-table-column>
        <a-table-column title="备注" align="center" data-index="remark" :ellipsis="true" />
        <a-table-column title="创建时间" align="center" data-index="createTime" width="180">
          <template #default="{ record }">
            <span>{{ parseTime(record.createTime) }}</span>
          </template>
        </a-table-column>
        <a-table-column title="操作" align="center" width="160" class-name="small-padding fixed-width">
          <template #default="{ record }">
            <a-tooltip content="修改" placement="top">
              <a-button v-hasPermi="['system:dict:edit']" type="link" @click="handleUpdate(record)">
                <FormOutlined />
              </a-button>
            </a-tooltip>
            <a-tooltip content="删除" placement="top">
              <a-button v-hasPermi="['system:dict:remove']" type="link" icon="" @click="handleDelete(record)">
                <DeleteOutlined />
              </a-button>
            </a-tooltip>
          </template>
        </a-table-column>
      </a-table>
      <div class="text-right mt-20px">
        <a-pagination
          v-show="total > 0"
          v-model:current="queryParams.pageNum" v-model:pageSize="queryParams.pageSize" :total="total"
          show-less-items @change="getList"
        />
      </div>
    </a-card>
    <!-- 添加或修改参数配置对话框 -->
    <a-modal v-model:open="dialog.visible" :mask-closable="false" :keyboard="false" :title="dialog.title" width="500px" append-to-body>
      <a-form ref="dictFormRef" :model="form" :rules="rules" :label-col="{ style: 'width:68px' }">
        <a-form-item label="字典名称" prop="dictName">
          <a-input v-model:value="form.dictName" placeholder="请输入字典名称" />
        </a-form-item>
        <a-form-item label="字典类型" prop="dictType">
          <a-input v-model:value="form.dictType" placeholder="请输入字典类型" />
        </a-form-item>
        <a-form-item label="备注" prop="remark">
          <a-textarea v-model:value="form.remark" placeholder="请输入内容" />
        </a-form-item>
      </a-form>
      <template #footer>
        <div class="dialog-footer">
          <a-button @click="cancel">
            取 消
          </a-button>

          <a-button type="primary" @click="submitForm">
            确 定
          </a-button>
        </div>
      </template>
    </a-modal>
  </div>
</template>
